import axios from 'axios';
import router from '@/router';
import store from '@/store';
import { BASE_URL } from './config';
import { getToken } from '@/utils/cookies';
import { ElLoading, ElMessage } from 'element-plus';
import type { LoadingInstance } from 'element-plus/lib/components/loading/src/loading';
// import _ from 'lodash';
export interface ErrorType {
  message?: string;
  type?: string;
  hideErr?: boolean;
  data?: any;
}
export interface ResponseType {
  data: Record<string, unknown>;
  code: number;
  msg?: string;
}

const axiosInstance = axios.create({
  baseURL: BASE_URL,
  timeout: 5000000,
  withCredentials: true,
  headers: {
    'Content-Type': 'application/json;charset=utf-8'
  }
});
let loading: LoadingInstance;
// 请求拦截器
axiosInstance.interceptors.request.use(
  (config: any) => {
    // Add X-Access-Token header to every request, you can add other custom headers here
    if (store.state.token && config.headers) {
      config.headers['Authorization'] = 'Bearer ' + store.state.token;
    }
    // debugger;
    if (config.isShowLoading !== 'no') {
      // _.throttle(() => {

      // });
      loading = ElLoading.service({
        lock: true,
        text: '正在加载中...',
        background: 'rgba(0, 0, 0, 0.5)'
      });
    }

    return config;
  },
  (error) => {
    Promise.reject(error);
  }
);

axiosInstance.interceptors.response.use(
  (response) => {
    setTimeout(() => {
      loading?.close();
    }, 500);

    const res = response.data;
    if (res.code) {
      if (Number(res.code) !== 200 && res.code !== 203) {
        if (res.code === 401) {
          store.commit('CLEAR_TOKEN');
          router.replace('/login');
          return Promise.reject({
            hideErr: true
          });
        }

        return Promise.reject(new Error(res.msg || 'Error'));
      } else {
        return res;
      }
    } else {
      return res;
    }
  },
  (error) => {
    setTimeout(() => {
      loading?.close();
    }, 500);
    let err = {};
    if (error.response) {
      const { data = {} } = error.response;
      err = {
        message: data.message || '请求异常',
        type: 'error'
      };
    } else if (error.message && error.message.includes('timeout')) {
      err = {
        message: '请求超时，请检查网络连接!',
        type: 'error'
      };
    }
    return Promise.reject(err);
  }
);

export function formateURLOnlyGet(
  link: string,
  params: Record<string, unknown>
): string {
  let url = link;
  const data = Object.entries(params);

  if (data.length) {
    url += url.indexOf('?') == -1 ? '?' : '';
    url += Object.entries(data)
      .map((item) => {
        return item[1].join('=');
      })
      .join('&');
  }
  return url;
}

export function errorHandler(
  reqPromise: Promise<any>,
  option: Record<string, unknown>
): Promise<any> {
  return reqPromise.catch((err) => {
    if (option.showError && !err.hideErr) {
      ElMessage({
        message: err.message || '请求异常',
        type: err.type || 'error',
        duration: 5 * 1000
      });
    }
    return Promise.reject(err);
  });
}

const defaultOption = {
  showError: true,
  config: {
    headers: {
      'Content-Type': 'application/json;charset=utf-8'
    }
  }
};
/**
 * GET请求方法
 * @param {String} url 请求地址
 * @param {json} params 请求参数
 */
export function getData(
  url: string,
  params: Record<string, unknown>,
  options = defaultOption
): Promise<any> {
  return errorHandler(
    axiosInstance.get(url, { params: { ...params } }),
    options
  );
}
export function putData(
  url: string,
  params?: Record<string, unknown>,
  options = defaultOption
): Promise<any> {
  const config = options.config;
  const data =
    config.headers && config.headers['Content-Type'] === 'multipart/form-data'
      ? params
      : JSON.stringify(params);

  return errorHandler(axiosInstance.put(url, data, config), options);
}
export function postData(
  url: string,
  params?: Record<string, unknown>,
  options = defaultOption
): Promise<any> {
  const config = options.config;
  const data =
    config.headers && config.headers['Content-Type'] === 'multipart/form-data'
      ? params
      : JSON.stringify(params);

  return errorHandler(axiosInstance.post(url, data, config), options);
}
export function deleteData(
  url: string,
  params: Record<string, unknown>,
  options = defaultOption
): Promise<any> {
  return errorHandler(axiosInstance.delete(url, { params }), options);
}
